<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input type="text" placeholder="please enter..." id="ipMsg">
    <button id="btn">发送消息</button>
    <button id="btnClose">断开连接</button>

    <script>
        // 发起远程连接请求websocket长连接
        var ws = new WebSocket('ws://localhost:8080');

        // 连接成功时打印一下
        ws.onopen = function () {
          console.log('ws onopen');
        //   ws.send('from client: hello');
        };

        // 收到服务端的消息时打印一下
        ws.onmessage = function (e) {
          console.log('ws onmessage');
          console.log('from server: ' + e.data);
        };

        ws.onerror = function(e){
            //处理连接错误
        }

        // 点击按钮给服务端发送消息
        btn.onclick = function(e){
            ws.send(ipMsg.value);
        }

        // 点击按钮断开与服务端的连接
        btnClose.onclick = function(e){
            ws.close()
            console.log("连接已断开");
        }

      </script>
</body>
</html>